package com.sanjishu.enterlab.electricity.sale.controller.sale;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.*;
import com.sanjishu.enterlab.electricity.sale.service.*;
import com.sanjishu.enterlab.electricity.sale.shiro.ShiroAdmin;
import com.sanjishu.enterlab.electricity.sale.utils.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("sale/companyInfo")
public class SaleCompanyController {

    @Autowired
    private CompanyBakService companyBakService;
    @Autowired
    private SaleApplyService saleApplyService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private CityService cityService;
    @Autowired
    private CompanySaleService companySaleService;
    @Autowired
    private ContractInfoService contractInfoService;
    @Autowired
    private ContractSettingService contractSettingService;
    @Autowired
    private UserSettingService userSettingService;
    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        Page<CompanyBak> companyBakPage = companyBakService.findCompanyBakByPage(loginUser.getId(),
                loginUser.getTypes(), null, null, null, null, 1);
        model.addAttribute("pageData", companyBakPage);
        return "sale/companies/index";
    }

    @RequestMapping(value = "page", method = RequestMethod.POST)
    public String page(String searchText, Integer searchTypes, String columnName, Integer sortType, Integer page, Model model) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        Page<CompanyBak> companyBakPage = companyBakService.findCompanyBakByPage(loginUser.getId(),
                loginUser.getTypes(), searchText, searchTypes, columnName, sortType, page);
        model.addAttribute("pageData", companyBakPage);
        model.addAttribute("searchText", searchText);
        model.addAttribute("searchTypes", searchTypes);
        return "sale/companies/page";
    }

    @RequestMapping(value = "connectWith", method = RequestMethod.POST)
    @ResponseBody
    public Response connectWith(Integer companyBakId) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        CompanyInfo companyInfo = companyInfoService.findByCompanyBakId(companyBakId);
        if (companyInfo != null && companyInfo.getStatus() == CompanyInfo.STATUS_SIGNED) {
            return Response.getError("当前企业已经签约，不能再关联了。");
        }
        SaleApply saleApply = saleApplyService.findByUserId(loginUser.getId(), companyBakId);
        if (saleApply != null) {
            return Response.getError("您的关联申请已经提交了。");
        }
        saleApply = saleApplyService.createApply(loginUser.getId(), companyBakId);
        CompanyBak companyBak = companyBakService.getById(companyBakId);
        if (companyBak.getUserId() == null) {
            saleApplyService.passApplyAuto(saleApply.getId(), loginUser.getId(), companyBakId);
            return Response.buildSuccess("关联成功。");
        }
        //String name = loginUser.getName() != null ? loginUser.getName() : loginUser.getUsername();
        //messageService.sendApplyMessage(name);
        return Response.buildSuccess("关联申请已经发送，请等待管理员审核。");

    }

    @RequestMapping(value = "settlementList", method = RequestMethod.GET)
    public String settlementList(Model model) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        UserSetting userSetting = userSettingService.findByUserId(loginUser.getId());
        Integer pageSize = (userSetting!= null && userSetting.getNum1() != null) ? userSetting.getNum1() : 0;
        Page<CompanyInfo> companyInfoPage = companyInfoService.findByAdminId(loginUser.getId(), 1, pageSize);
        model.addAttribute("pageData", companyInfoPage);
        model.addAttribute("userSetting", userSetting);
        return "sale/settlements/index";
    }

    @RequestMapping(value = "myContracts", method = RequestMethod.GET)
    public String myContracts(Model model) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        UserSetting userSetting = userSettingService.findByUserId(loginUser.getId());
        Integer pageSize = (userSetting!= null && userSetting.getNum1() != null) ? userSetting.getNum1() : 0;
        Page<CompanyInfo> companyInfoPage = companyInfoService.findMyContracts(loginUser.getId(), 1, pageSize);
        model.addAttribute("pageData", companyInfoPage);
        model.addAttribute("userSetting", userSetting);
        return "sale/myContracts/index";
    }

    @RequestMapping(value = "newContract", method = RequestMethod.GET)
    public String newContract(Model model) {
        List<City> cityList = cityService.getCityList();
        model.addAttribute("cityList", cityList);
        if (cityList != null && cityList.size()>0) {
            List<City> areaList = cityService.getArea(cityList.get(0).getId());
            model.addAttribute("areaList", areaList);
        }
        return "sale/settlements/newContract";
    }

    @RequestMapping(value = "newContract/{id}", method = RequestMethod.GET)
    public String newContractById(@PathVariable Integer id, Model model) {
        CompanyBak companyBak = companyBakService.getById(id);
        model.addAttribute("companyBak", companyBak);
        List<City> cityList = cityService.getCityList();
        model.addAttribute("cityList", cityList);
        if (companyBak != null) {
            City city = cityService.getAreaAndCity(companyBak.getCityId());
            model.addAttribute("city", city);
            if (city != null) {
                List<City> areaList = null;
                if (city.getParentId() == 1) {
                    areaList = cityService.getArea(city.getId());
                } else {
                    areaList = cityService.getArea(city.getParentId());
                }
                model.addAttribute("areaList", areaList);
            }
        }
        return "sale/settlements/newContract";
    }

    @RequestMapping(value = "edit/{companyId}", method = RequestMethod.GET)
    public String editContract(@PathVariable Integer companyId, Model model) {
        CompanyInfo companyInfo = companyInfoService.findById(companyId);
        DetailInfo detailInfo = companyInfoService.findByCompanyId(companyId);
        if (companyInfo != null) {
            City city = cityService.getAreaAndCity(companyInfo.getCityId());
            model.addAttribute("city", city);
            if (city != null) {
                List<City> areaList = null;
                if (city.getParentId() == 1) {
                    areaList = cityService.getArea(city.getId());
                } else {
                    areaList = cityService.getArea(city.getParentId());
                }
                model.addAttribute("areaList", areaList);
            }
        }
        ContractInfo contractInfo = contractInfoService.findByCompanyAndTime(companyId);
        if (contractInfo != null) {
            ContractSetting contractSetting = contractSettingService.findByContractId(contractInfo.getId());
            model.addAttribute("contractSetting", contractSetting);
        }
        List<City> cityList = cityService.getCityList();
        model.addAttribute("cityList", cityList);
        model.addAttribute("companyInfo", companyInfo);
        model.addAttribute("detailInfo", detailInfo);
        model.addAttribute("contractInfo", contractInfo);
        return "sale/settlements/editContract";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public Response create(String companyName, String creditCode, String operName, String address, String elecFor,
                           String contractName, String contractPhone, String wxNum, Integer cityId, String capital,
                           String voltageStep, String elecAccount, String transformerCapacity,
                           String elecConsumption, String detailCategory, String bankName,
                           String bankAccountName, String bankAccount, String contactPhone,
                           String fax, String tradeCycle, String startAt, String endedAt,
                           String description, Integer settingType, BigDecimal customerRate,
                           BigDecimal bottomPrice, Integer companyBakId) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        CompanyInfo companyInfo = companyInfoService.getByName(companyName);
        if (companyInfo != null) {
            if (companyInfo.getAdminId() != null) {
                if (companyInfo.getAdminId() != loginUser.getId()) {
                    return Response.getError("当前公司已经被其他销售绑定了");
                } else {
                    return Response.getError("你已经绑定当前公司了，可以在合同列表中查看");
                }
            } else {
                return Response.getError("当前公司已经被其他销售绑定了");
            }
        } else {
            return companySaleService.generalContractAuto(companyName,creditCode, operName, address, elecFor,
                    contractName, contractPhone,wxNum,cityId, capital, voltageStep, elecAccount, transformerCapacity,
                    elecConsumption, detailCategory, bankName, bankAccountName, bankAccount, contactPhone, fax,
                    tradeCycle, startAt, endedAt, description, settingType, customerRate, bottomPrice,
                    loginUser.getId(), companyBakId);
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Response update(Integer companyId, Integer contractId, Integer detailId,
                           String companyName, String creditCode, String operName, String address, String elecFor,
                           String contractName, String contractPhone, String wxNum, Integer cityId, String capital,
                           String voltageStep, String elecAccount, String transformerCapacity,
                           String elecConsumption, String detailCategory, String bankName,
                           String bankAccountName, String bankAccount, String contactPhone,
                           String fax, String tradeCycle, String startAt, String endedAt,
                           String description, Integer settingType, BigDecimal customerRate, BigDecimal bottomPrice) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        CompanyInfo companyInfo = companyInfoService.getByName(companyName);
        if (companyInfo != null && companyInfo.getAdminId() != loginUser.getId()) {
                return Response.getError("当前公司已经被其他销售绑定了");
        }
        return companySaleService.updateCompanyInfo(companyId, contractId, detailId,
                companyName,creditCode, operName, address, elecFor,
                contractName, contractPhone,wxNum,cityId, capital, voltageStep, elecAccount, transformerCapacity,
                elecConsumption, detailCategory, bankName, bankAccountName, bankAccount, contactPhone, fax,
                tradeCycle, startAt, endedAt, description, settingType, customerRate, bottomPrice, loginUser.getId());

    }


    @RequestMapping(value = "searchCompany", method = RequestMethod.POST)
    public String searchCompany(String companyName, Model model) {
        CompanyBak companyBak = companyBakService.getOneByName(companyName);
        model.addAttribute("companyBak", companyBak);
        if (companyBak != null) {
            City city = cityService.getAreaAndCity(companyBak.getCityId());
            model.addAttribute("city", city);
            if (city != null) {
                List<City> areaList = null;
                if (city.getParentId() == 1) {
                    areaList = cityService.getArea(city.getId());
                } else {
                    areaList = cityService.getArea(city.getParentId());
                }
                model.addAttribute("areaList", areaList);
            }
        }
        List<City> cityList = cityService.getCityList();
        model.addAttribute("cityList", cityList);

        return "sale/settlements/newPanel";
    }

    @RequestMapping(value = "updateUserSetting", method = RequestMethod.POST)
    @ResponseBody
    public Response updateUserSetting(Integer selectValue1, Integer selectValue2, Integer selectValue3) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        UserSetting userSetting = userSettingService.findByUserId(loginUser.getId());
        if (userSetting != null) {
            userSettingService.updateUserSetting(loginUser.getId(), selectValue1, selectValue2, selectValue3);
        } else {
            userSettingService.createUserSetting(loginUser.getId(), selectValue1, selectValue2, selectValue3);
        }
        return Response.buildSuccess("设置成功。");
    }

    @RequestMapping(value = "cancelApply", method = RequestMethod.POST)
    @ResponseBody
    public Response cancelApply(Integer applyId) {
        Subject subject = SecurityUtils.getSubject();
        ShiroAdmin loginUser = (ShiroAdmin) subject.getPrincipal();
        return saleApplyService.cancelApply(loginUser.getId(), applyId);
    }


}
